# -*- coding:utf-8 -*-
# pip install requests
# @Time    : 2021/06/07 11:22
# @Author  : wangleip
# @Remark  : 企查查Api
# @Software: PyCharm

import requests
import config
import time
import hashlib
import json
import db_executor


class QiChacha:
    """
    企查查相关接口处理类
    """

    def __init__(self):
        self.app_key = config.QICHACHA_KEY
        self.secret_key = config.QICHACHA_SECRET_KEY
        self.host = config.QICHACHA_API_HOST
        self.default_header = {"User-Agent": config.DEFAULT_REQUEST_HEADER_USER_AGENT}
        self.default_encode = "utf-8"

    def get_request(self, url, paramstr):
        """
        提交API请求
        :param url: 请求url
        :param paramstr 请求参数字符串，例如：arg1=1&arg2=2&arg3=3...
        :return: 请求结果json数据
        """
        # Http请求头设置
        timespan = str(int(time.time()))
        token = self.app_key + timespan + self.secret_key
        hl = hashlib.md5()
        hl.update(token.encode(encoding=self.default_encode))
        token = hl.hexdigest().upper()

        url = self.host + url + "?key=" + self.app_key + "&" + paramstr
        headers = {'Token': token, 'Timespan': timespan}
        response = requests.get(url, headers=headers)
        return json.loads(response.content.decode())

    def get_company_details(self, name):
        """
        根据公司名称获取公司详情信息
        :param name: 公司名称
        :return: 公司详情
        """
        url = "{}/ECIV4/GetDetailsByName".format(self.host)
        pass

    def save_baidu_map_data(self, baidu_map_data):
        """
        保存麦度检索结果
        :param baidu_map_data: 百度检索结果JSON数据
        :return:
        """
        # {'name': '新时代大厦', 'location': {'lat': 39.980227, 'lng': 116.371776}, 'address': '北京市海淀区花园路7号', 'province': '北京市', 'city': '北京市', 'area': '海淀区', 'street_id': '98656baf67433ac6471a3245', 'telephone': '(010)82803813', 'detail': 1, 'uid': '98656baf67433ac6471a3245'}
        # SQL语句模板
        exists_temp_sql = "IF EXISTS(SELECT [Uid] FROM YuanChacha.BaiduMapData WHERE [Uid]=N'{}') \n"
        insert_temp_sql = " INSERT INTO YuanChacha.BaiduMapData([Uid],[Name],[Address],[Province],[City],[Area],[StreetId],[Telephone],[Lat],[Lng],[CreateTime]) VALUES (N'{}',N'{}',N'{}',N'{}',N'{}',N'{}',N'{}',N'{}',N'{}',N'{}',GETDATE()) \n"
        update_temp_sql = " UPDATE YuanChacha.BaiduMapData SET Name=N'{}',[Address]=N'{}',[Province]=N'{}',[City]=N'{}',[Area]=N'{}',[StreetId]=N'{}',[Telephone]=N'{}',[Lat]=N'{}',[Lng]=N'{}' WHERE [Uid]=N'{}' \n"

        # 拼接SQL
        sql = exists_temp_sql.format(baidu_map_data["uid"])
        sql += update_temp_sql.format(baidu_map_data["name"], baidu_map_data["address"], baidu_map_data["province"],
                                      baidu_map_data["city"], baidu_map_data["area"],
                                      baidu_map_data["street_id"], baidu_map_data.get("telephone",""),
                                      baidu_map_data["location"]["lat"], baidu_map_data["location"]["lng"],
                                      baidu_map_data["uid"])
        sql += "ELSE \n"
        sql += insert_temp_sql.format(baidu_map_data["uid"], baidu_map_data["name"], baidu_map_data["address"],
                                      baidu_map_data["province"], baidu_map_data["city"], baidu_map_data["area"],
                                      baidu_map_data["street_id"], baidu_map_data.get("telephone",""),
                                      baidu_map_data["location"]["lat"], baidu_map_data["location"]["lng"])
        # print(sql)
        # 执行SQL
        executor = db_executor.DbExecutor()
        executor.execute(sql)

    def save_company(self, company, uid):
        """
        保存检索结果到数据库
        :param company: 企查查公司数据
        :param uid: 百度查询结果ID
        :return:
        """
        # SQL语句模板
        exists_temp_sql = "IF EXISTS(SELECT KeyNo FROM YuanChacha.Company WHERE KeyNo = N'{}') \n"
        insert_temp_sql = " INSERT INTO YuanChacha.Company(KeyNo,Name,OperName,StartDate,Status,No,CreditCode) VALUES (N'{}',N'{}',N'{}',N'{}',N'{}',N'{}',N'{}') \n"
        update_temp_sql = " UPDATE YuanChacha.Company SET Name=N'{}',OperName=N'{}',StartDate=N'{}',Status=N'{}',No=N'{}',CreditCode=N'{}' WHERE  KeyNo = N'{}' \n"

        map_notexists_temp_sql = "IF NOT EXISTS(SELECT KeyNo FROM YuanChacha.BaiduMapData_Company WHERE [Uid]=N'{}' AND KeyNo = N'{}') \n"
        map_int_temp_sql = "INSERT INTO [YuanChacha].[BaiduMapData_Company]([Uid],[KeyNo],[MatchStatus],[CreateTime]) VALUES (N'{}',N'{}',-1,GETDATE()) \n"

        # 拼接SQL
        sql = exists_temp_sql.format(company["KeyNo"])
        sql += update_temp_sql.format(company["Name"], company["OperName"], company["StartDate"], company["Status"],
                                      company["No"],
                                      company["CreditCode"], company["KeyNo"])
        sql += "ELSE \n"
        sql += insert_temp_sql.format(company["KeyNo"], company["Name"], company["OperName"], company["StartDate"],
                                      company["Status"], company["No"], company["CreditCode"])

        sql += map_notexists_temp_sql.format(uid, company["KeyNo"])
        sql += map_int_temp_sql.format(uid, company["KeyNo"])

        # print(sql)
        # 执行SQL语句
        executor = db_executor.DbExecutor()
        executor.execute(sql)

    def save_search_result(self, baidu_map_data, companys):
        """
        保存检索结果到数据库
        :param baidu_map_data: 百度检索结果
        :param companys: 企查查检索结果
        :return:
        """
        self.save_baidu_map_data(baidu_map_data)
        uid = baidu_map_data["uid"]
        for item in companys:
            self.save_company(item, uid)

    def search_company(self, keyword, citycode):
        """
        根据关键字查询公司信息
        :param keyword: 关键字
        :param citycode: 城市编码
        :return: 查询结果json数据
        """
        url = "/ECIV4/Search"
        params = "keyword={}$cityCode={}".format(keyword, citycode)
        json = self.get_request(url, params)

        """
        请求结果JSON数据格式如下：
        {
          "Paging":{"PageSize":10,"PageIndex":1,"TotalRecords":1},
          "Result":[{"KeyNo":"98f9d89e62f0d210ce0338293eeb5848","Name":"加拿大怡美代科有限公司北京代表处","OperName":"程鑫","StartDate":"2006-04-03 00:00:00","Status":"吊销","No":"110000400155398","CreditCode":"911100007877508404"}],
          "Status":"200",
          "Message":"【有效请求】查询成功",
          "OrderNumber":"ECI2021060715470993808845"
        }
        当无符合条件数据时:{"Paging":null,"Result":null,"Status":"201","Message":"【有效请求】查询无结果","OrderNumber":"ECI2021060715470923305082"}
        """
        # print(keyword)
        # print(json)

        if json["Status"] == "200":
            return json["Result"]
        else:
            return None

    def search(self, keywords, citycode):
        """
        根据关键字列表和城市编码查询企业信息
        :param keywords: 关键字列表
        :param citycode: 6位城市编码
        :return:
        """
        for item in keywords:
            self.search_company(item, citycode)

    def search_map_data(self, map_data, citycode):
        """
        根据百度api检索结果来检索企查查数据
        :param map_data: 百度api检索结果JSON数据
        :param citycode: 6位城市编码
        :return:
        """
        for item in map_data:
            companys = self.search_company(item["name"], citycode)
            if companys is not None:
                self.save_search_result(item, companys)

    def get_company_info(self, name):
        """
        获取公司工商注册信息
        :param name: 企业名称
        :return:
        """
        url ="/ECIInfoVerify/GetInfo".format()
        params = "searchKey={}".format(name)
        json = self.get_request(url, params)
        if json["Status"] == "200":
            return json["Result"]
        else:
            return None